package com.lej.my.information

import android.text.InputFilter
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.alibaba.android.arouter.facade.annotation.Route
import com.lej.core.base.BaseFragment
import com.lej.core.common.PCacheInfo
import com.lej.core.dsl.dp
import com.lej.core.router.CRouter
import com.lej.core.utils.StringUtil
import com.lej.core.utils.extention.clickLaunch
import com.lej.core.utils.extention.toast
import com.lej.dataservice.club.http.checkData
import com.lej.my.BR
import com.lej.my.MyActivity
import com.lej.my.R
import com.lej.my.databinding.MyFragmentInformationBinding
import com.lej.my.http.myApiService
import com.qmuiteam.qmui.kotlin.onClick
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 *  author: cjq
 *  date  : 2022/6/21 0021
 *  desc  :
 */
@Route(path = CRouter.myInformation)
class MyInformationFragment : BaseFragment<MyFragmentInformationBinding, MyInformationVM>() {

    override fun initData() {
        super.initData()
        setName()
        binding.tvName.onClick {
            viewModel.isNormalLayout.value = false
        }
        setEditTextInhibitInputSpeChat(binding.etName)
        binding.btnNegative.onClick {
            viewModel.name.value = PCacheInfo.nick
            viewModel.isNormalLayout.value = true
        }
        binding.btnPositive.clickLaunch {
            if (viewModel.updateUserName()) {
                "修改成功".toast()
                setName()
                activity?.let { (it as MyActivity).setUserName(PCacheInfo.nick) }
                viewModel.isNormalLayout.value = true
            }
        }
        createQrcode()
    }

    private fun setName() {
        binding.tvTips.text = StringUtil.getString(R.string.my_qrcode, PCacheInfo.nick)
        binding.tvName.text = StringUtil.getString(R.string.my_nick, PCacheInfo.nick)
        viewModel.name.value = PCacheInfo.nick
    }

    /**
     * 只能输中英文，过滤空格，限制输入长度
     */
    private fun setEditTextInhibitInputSpeChat(editText: EditText) {
        val filter = InputFilter { source, _, _, _, _, _ ->
            val speChat =
                "[a-zA-Z|\u4e00-\u9fa5]+"
            val pattern: Pattern = Pattern.compile(speChat)
            val matcher: Matcher = pattern.matcher(source.toString())
            if (!matcher.matches()) "" else null
        }
        val emptyFilter = InputFilter { source, _, _, _, _, _ ->
            if (source.equals(" ")) "" else null
        }
        val lengthFilter = InputFilter.LengthFilter(8)
        editText.filters = arrayOf(filter, emptyFilter,lengthFilter)
    }

    private fun createQrcode() {
        lifecycleScope.launch {
            kotlin.runCatching {
                val qrcode = myApiService.getQrCode().checkData().get("url").asString
                val bitmap = withContext(Dispatchers.IO) {
                    QRCodeEncoder.syncEncodeQRCode(qrcode, 100.dp)
                }
                binding.ivQrcode.setImageBitmap(bitmap)
            }.onFailure {
                binding.ivQrcode.setImageResource(R.drawable.ic_load_place_error)
            }
        }
    }

    override fun getLayout(): Int = R.layout.my_fragment_information

    override fun initVariableId(): Int = BR.vm
}